package com.magenta.mrs.settings;

import org.w3c.dom.*;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
/*
* Project: Maxoptra
* Author: Kirill Sychin
* Date: 31.10.2008 10:50:43
*
* Copyright (c) 1999-2008 Magenta Corporation Ltd. All Rights Reserved.
* Magenta Technology proprietary and confidential.
* Use is subject to license terms.
*/

public class ParseConfigXml {

    public static Map<String, Group> loadConfig(InputStream file) {

        Map<String, Group> res = new HashMap<String, Group>();

        try {
            DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
            Document doc = docBuilder.parse(file);
            doc.getDocumentElement().normalize();

            NodeList listOfRegion = doc.getElementsByTagName("group");
            for (int s = 0; s < listOfRegion.getLength(); s++) {

                Node regionNode = listOfRegion.item(s);
                if (regionNode.getNodeType() == Node.ELEMENT_NODE) {
                    Element regionElement = (Element)regionNode;


                    final Group group = new Group();
                    Map<String, String> propertiesMap = new HashMap<String, String>();
                    NodeList properties = regionElement.getElementsByTagName("property");
                    for (int i = 0; i < properties.getLength(); i++) {
                        Node property = properties.item(i);
                        if (property.getNodeType() == Node.ELEMENT_NODE) {
                            final NamedNodeMap values = property.getAttributes();
                            propertiesMap.put(values.getNamedItem("name").getNodeValue(), values.getNamedItem("value").getNodeValue());
                        }
                    }
                    group.setPropeties(propertiesMap);
                    res.put(regionNode.getAttributes().getNamedItem("name").getNodeValue(), group);
                }
            }
        } catch (SAXParseException err) {
            System.out.println("** Parsing error" + ", line "
                    + err.getLineNumber() + ", uri " + err.getSystemId());
            System.out.println(" " + err.getMessage());
        } catch (SAXException e) {
            Exception x = e.getException();
            ((x == null) ? e : x).printStackTrace();
        } catch (Throwable t) {
            t.printStackTrace();
        }
        return res;
    }

}
